package com.kkd.kkdapp.adapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.CreditorIsRightsParticularsActivity;
import com.kkd.kkdapp.activity.CreditorIsRightsTenderAffirmActivity;
import com.kkd.kkdapp.activity.ForTenderActivity;
import com.kkd.kkdapp.activity.LoginActivity;
import com.kkd.kkdapp.http.entity.TransferEntity;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.Tools;
import com.kkd.kkdapp.view.RoundProgressBar;

public class TransferAdapter extends BaseAdapter {
	private List<TransferEntity> datalist;
	private Context mContext;
	private double balance;
	private Toast mToast;
	private String securityUrl = "";
	public boolean mIsFirstAnimation = true;
	public boolean isShowProfit = false;

	public TransferAdapter(Context context, ArrayList<TransferEntity> data) {
		mContext = context;
		datalist = data;

	}

	public void setSecurityUrl(String securityUrl) {
		this.securityUrl = securityUrl;
	}

	@Override
	public int getCount() {
		return datalist.size();
	}

	@Override
	public Object getItem(int position) {

		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		return getBidView(position, convertView, parent);
	}

	/**
	 * getBidView:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 * @param position
	 * @param convertView
	 * @param parent
	 */
	private View getBidView(final int position, View convertView,
			ViewGroup parent) {
		ViewHolder mViewHolder;

		if (convertView == null
				|| !(convertView.getTag() instanceof ViewHolder)) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.transfer_list_item, null);
			mViewHolder = new ViewHolder();
			// 上部点击进入标的详情界面
			mViewHolder.top = (RelativeLayout) convertView
					.findViewById(R.id.top);
			// 标题
			mViewHolder.refund_name = (TextView) convertView
					.findViewById(R.id.refund_name);
			// 标的类型
			// mViewHolder.type_bg = (PorterShapeImageView) convertView
			// .findViewById(R.id.type_bg);
			mViewHolder.type_tv = (TextView) convertView
					.findViewById(R.id.type_tv);
			mViewHolder.leftCount_tv = (TextView) convertView
					.findViewById(R.id.leftCount_tv);

			// 年利率
			mViewHolder.interest_tv = (TextView) convertView
					.findViewById(R.id.interest_tv);
			// 加息
			mViewHolder.rise_tv1 = (TextView) convertView
					.findViewById(R.id.rise_tv1);

			// 理财期限
			mViewHolder.deadline_tv = (TextView) convertView
					.findViewById(R.id.deadline_tv);
			// 理财期限单位
			mViewHolder.deadline_company_tv = (TextView) convertView
					.findViewById(R.id.deadline_company_tv);
			// 按钮
			mViewHolder.bid = (LinearLayout) convertView.findViewById(R.id.bid);
			mViewHolder.progressBar = (RoundProgressBar) convertView
					.findViewById(R.id.progressBar1);
			mViewHolder.bid_tv1 = (TextView) convertView
					.findViewById(R.id.bid_tv1);
			mViewHolder.bid_tv2 = (TextView) convertView
					.findViewById(R.id.bid_tv2);

			mViewHolder.zhanqi_count = (TextView) convertView
					.findViewById(R.id.zhanqi_count);

			mViewHolder.tuijian = (ImageView) convertView
					.findViewById(R.id.tuijian);
			convertView.setTag(mViewHolder);

		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}
		renderBidView(position, mViewHolder);

		return convertView;

	}

	/**
	 * gotoOldLogic:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	private void renderBidView(final int position, final ViewHolder mViewHolder) {

		mViewHolder.tuijian.setBackgroundColor(Color.parseColor(datalist.get(
				position).getTransTypeColor()));
		mViewHolder.tuijian.setVisibility(View.VISIBLE);
		/*************** 标题 *****************/
		mViewHolder.refund_name.setText(datalist.get(position).getTitle());
		/*************** 标的类型 **************/
		DecimalFormat df = new DecimalFormat("###.00");
		String pa = df.format(datalist.get(position).getPerAmount() / 100.0f);
		mViewHolder.type_tv.setText("每份价格: "
				+ pa + "元");

		mViewHolder.leftCount_tv.setText(datalist.get(position).getLeftCount());

		/**************** 年利率 **************/
		mViewHolder.interest_tv.setTag(position);
		mViewHolder.rise_tv1.setTag(position);
		String interestDisplay = datalist.get(position).getInterestDisplay();
		mViewHolder.interest_tv.setText(interestDisplay);
		if (interestDisplay.indexOf("+") == -1) {
			mViewHolder.interest_tv.setText(Tools.intOrDouble(Double
					.parseDouble(interestDisplay)));
			mViewHolder.rise_tv1.setText("");
		} else {
			String[] idp = interestDisplay.split("\\+");
			mViewHolder.interest_tv.setText(Tools.intOrDouble(Double
					.parseDouble(idp[0])));
			mViewHolder.rise_tv1.setText("+"
					+ Tools.intOrDouble(Double.parseDouble(idp[1])) + "%");
		}

		/*************** 标的期限 *****************/
		mViewHolder.deadline_tv.setTag(position);
		if (datalist.get(position).getLeftTermMonthDesc() > 0) {
			mViewHolder.deadline_tv.setVisibility(View.VISIBLE);
			mViewHolder.deadline_company_tv.setVisibility(View.VISIBLE);
			mViewHolder.deadline_tv.setText(datalist.get(position)
					.getLeftTermMonthDesc() + "");
			mViewHolder.deadline_company_tv.setText("个月");
		} else {
			mViewHolder.deadline_tv.setVisibility(View.INVISIBLE);
			mViewHolder.deadline_company_tv.setVisibility(View.GONE);
		}

		int leftTermDayDesc = datalist.get(position).getLeftTermDayDesc();
		if (leftTermDayDesc > 0) {
			mViewHolder.zhanqi_count.setVisibility(View.VISIBLE);
			mViewHolder.zhanqi_count.setText(leftTermDayDesc + "天");
		} else {
			mViewHolder.zhanqi_count.setVisibility(View.GONE);
		}

		/***************** 标的状态 *******************/
		int transferProgress = (int) datalist.get(position)
				.getTransferProgress();
		mViewHolder.progressBar.setRoundWidth(SystemUtils.dip2px(mContext, 3));
		// 进度色值
		mViewHolder.progressBar.setCricleProgressColor(0xffff5a00);
		// 圆环色值
		mViewHolder.progressBar.setCricleColor(0xfff4f4f4);
		mViewHolder.progressBar.setProgress(transferProgress == 0 ? 1
				: transferProgress);
		mViewHolder.progressBar.setTag(position);
		mViewHolder.progressBar.setVisibility(View.GONE);

		mViewHolder.bid.setTag(position);
		mViewHolder.bid.setBackgroundResource(R.drawable.tender_bt_selector);
		mViewHolder.bid.setVisibility(View.VISIBLE);
		mViewHolder.bid.setEnabled(true);
		mViewHolder.bid.setClickable(true);
		mViewHolder.bid_tv1.setVisibility(View.GONE);
		mViewHolder.bid_tv2.setVisibility(View.GONE);

		int transferStatus = datalist.get(position).getTransferStatus();
		switch (transferStatus) {
		case 10:
		case 20:
		case 5002:// 可投标状态或倒计时状态
			mViewHolder.progressBar.setVisibility(View.VISIBLE);
			mViewHolder.bid.setBackgroundResource(R.drawable.tender_img_gou);
			mViewHolder.bid.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {

					SystemUtils.onEvent("Regular_Bid", 1);

					try {

						if (PreferenceUtils.getInstance().getLogin(mContext) == 0) { // 登陆验证

							if (PreferenceUtils.getInstance().getAutonym(
									mContext) == 1) { // 身份认证

								if (PreferenceUtils.getInstance()
										.getBoundBankCard(mContext) == 1) { // 判定银行卡是否绑定
									gotoTenderActivity(datalist.get(position));
								} else {
									getAccountInfo(datalist.get(position));

								}

							} else {
								gotoTrueIDVerifyActivity(datalist.get(position));

							}

						} else {

							Intent intent = new Intent(mContext,
									LoginActivity.class);
							mContext.startActivity(intent);

						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			break;
		case 5003:// 已满标
			// String bidType = datalist.get(position).getBidType();
			// if (bidType.equals("401")) {
			// mViewHolder.bid.setBackgroundResource(R.drawable.icon_yitouman);
			// } else {
			// mViewHolder.bid
			// .setBackgroundResource(R.drawable.tender_img_man);
			// }
			mViewHolder.bid.setClickable(false);
			break;
		case 5004:// 还款中
			mViewHolder.bid
					.setBackgroundResource(R.drawable.tender_img_returning);
			mViewHolder.bid.setClickable(false);
			break;
		case 5005:// 已还款
			mViewHolder.bid.setClickable(false);
			mViewHolder.bid
					.setBackgroundResource(R.drawable.tender_img_returnd);

			break;

		default:
			mViewHolder.bid.setVisibility(View.GONE);
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
			break;
		}
		mViewHolder.top.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				Intent intent = new Intent(mContext,
						CreditorIsRightsParticularsActivity.class);
				intent.putExtra("transferId", datalist.get(position)
						.getTransferId());
				mContext.startActivity(intent);

			}
		});

	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo(final TransferEntity tenderData) {

		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
							if (balance == 0) {
								gotoAddBankActivity(tenderData);

							} else {
								gotoTenderActivity(tenderData);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
					}
				});
	}

	private class ViewHolder {
		RelativeLayout top;
		TextView refund_name;
		TextView interest_tv;
		TextView deadline_tv;
		TextView zhanqi_count;
		LinearLayout bid;
		TextView bid_tv1;
		TextView bid_tv2;
		// PorterShapeImageView type_bg;
		RoundProgressBar progressBar;
		TextView type_tv;
		TextView deadline_company_tv;
		TextView rise_tv1;
		TextView leftCount_tv;
		ImageView tuijian;
	}

	public void showToast(String hintLanguage) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		mToast = Toast.makeText(mContext, hintLanguage, Toast.LENGTH_SHORT);
		mToast.show();
	}

	public void showToast(int hintLanguage) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		mToast = Toast.makeText(mContext, hintLanguage, Toast.LENGTH_SHORT);
		mToast.show();
	}

	public void gotoTenderActivity(TransferEntity tenderData) {
		if(tenderData.getIsOwner()== 1){
			showToast("您无法购买自己转让的债权");
		}else {
			Intent intent = new Intent(mContext,
					CreditorIsRightsTenderAffirmActivity.class);
			Gson gson = new Gson();
			intent.putExtra("json", gson.toJson(tenderData));
			mContext.startActivity(intent);	
		}
		
	}

	public void gotoTrueIDVerifyActivity(TransferEntity tenderData) {
		Intent intent = new Intent(mContext, ForTenderActivity.class);
		intent.putExtra("enterTypeFlag", 6);
		Gson gson = new Gson();
		intent.putExtra("json", gson.toJson(tenderData));
		mContext.startActivity(intent);
	}

	public void gotoAddBankActivity(TransferEntity tenderData) {
		Intent intent = new Intent(mContext, ForTenderActivity.class);
		intent.putExtra("enterTypeFlag", 6);
		Gson gson = new Gson();
		intent.putExtra("json", gson.toJson(tenderData));
		mContext.startActivity(intent);

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mIsFirstAnimation = false;
		}
	};

	/**
	 * notifyKkdDataSetChanged:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	public void notifyKkdDataSetChanged() {
		notifyDataSetChanged();
		if (mIsFirstAnimation) {
			handler.sendEmptyMessageDelayed(1, 1000);
		}
	}

	public void profitShow(boolean isShow) {
		isShowProfit = isShow;
		notifyDataSetChanged();
	}

	private boolean isHasMore = false;

	public void hasMore(boolean b) {
		isHasMore = b;
		notifyDataSetChanged();
	}

}